var projectId =  this.getQueryString("projectId")||'88888888888';

$(function(){
	initTopPage(); // 初始化第一步
	initBottomPage(); // 第二步
});

function initTopPage() {
	getPowerSSEEchart(); // 归一化类内距离统计图
	getContourCoeEchart(); // 轮廓系数
	getContourDBIEchart(); // 轮廓系数-DBI
}
function initBottomPage() {
	getClusterScatterEchart(); // 聚类散点图
	getFeatureEchart(); // 时序图
}
function firstCal() {
	//展示进度窗口
	$('#wizardMask').show();
	$('#progressDiv').show();
	$('#progressDiv').draggable();
	//循环查看状态
    var t = setInterval(function(){
    	$.ajax({
            dataType: "json",
			data:{planId:projectId},
			url: '../pv/executivemeoscn/getProgressInfo'
        }).done(function(res) {
        	var r = eval("("+res.result+")");
        	$('#progressText').html(r.result);
        	$('#progressText')[0].scrollTop = $('#progressText')[0].scrollHeight;
    	});
    }, 1000);
    $('#progressClose').click(function(){
    	layui.use('layer', function(){ //独立版的layer无需执行这一句
			var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
			
			layer.confirm('是否确定停止计算', {icon: 3, title:'提示'}, function(index){
				killNowTask("101");
				$('#progressDiv').hide();
				$('#wizardMask').hide();
				clearInterval(t);
				layer.close(index);
			});
		});
	});

	$.ajax({
		dataType: "json",
		data:{planId:projectId,modelId:"101",type:1},
		url: "../pv/executivemeoscn/implementExe"
	}).done(function(res) {
		clearInterval(t);
		$('#progressText').html(res.result);
    	$('#progressText')[0].scrollTop = $('#progressText')[0].scrollHeight;
    	sleep(3000);
    	$('#wizardMask').hide();
		$('#progressDiv').hide();
		$('#progressText').html("");
		initTopPage();
	}).fail(function(data, status, xhr){
		clearInterval(t);
	});
}
function secondCal() {
	layui.use('layer', function(){
		var $ = layui.jquery, layer = layui.layer;
		layer.ready(function () {
			layer.prompt({title: '输入聚类数量'}, function(val, index){
				if(!isNaN(parseFloat(val)) && isFinite(val)) {
					layer.close(index);
					//展示进度窗口
					$('#wizardMask').show();
					$('#progressDiv').show();
					$('#progressDiv').draggable();
					//循环查看状态
				    var t = setInterval(function(){
				    	$.ajax({
				            dataType: "json",
							data:{planId:projectId},
							url: '../pv/executivemeoscn/getProgressInfo'
				        }).done(function(res) {
				        	var r = eval("("+res.result+")");
				        	$('#progressText').html(r.result);
				        	$('#progressText')[0].scrollTop = $('#progressText')[0].scrollHeight;
				    	});
				    }, 1000);
				    $('#progressClose').click(function(){
						layer.confirm('是否确定停止计算', {icon: 3, title:'提示'}, function(index){
							killNowTask("102");
							$('#progressDiv').hide();
							$('#wizardMask').hide();
							clearInterval(t);
							layer.close(index);
						});
					});
			
					$.ajax({
						dataType: "json",
						data:{planId:projectId,modelId:"102",type:2, exeNum: val},
						url: "../pv/executivemeoscn/implementExe"
					}).done(function(res) {
						clearInterval(t);
						$('#progressText').html(res.result);
				    	$('#progressText')[0].scrollTop = $('#progressText')[0].scrollHeight;
				    	sleep(3000);
				    	$('#wizardMask').hide();
						$('#progressDiv').hide();
						$('#progressText').html("");
						initBottomPage();
					}).fail(function(data, status, xhr){
						clearInterval(t);
					});
				} else {
					layer.msg('只能输入数字');
					return;
				}
			});
		});
	});
}
function sleep(NumMillis) {
	var nowTime = new Date();
    var exitTime = nowTime .getTime() + NumMillis;
    while (true) {
    	now = new Date();
        if (now.getTime() > exitTime) {
            return;
        }
    }
}
function killNowTask(modelId){
	var method ='killClassicTask';
	invoke(method, {modelId:modelId,planId:projectId}, function(data){
    });
};

function getPowerSSEEchart() {
	JyyModelLoading.start("firstEchartDiv");
	$.when(getEcahtData({projectId:projectId}, "selectPowerSSEEchatData")).done(function(echatData){
		createEchat(echatData.res, 1);
		JyyModelLoading.end("firstEchartDiv");
	});
}
function getContourCoeEchart() {
	JyyModelLoading.start("secondEchartDiv");
	$.when(getEcahtData({projectId:projectId}, "selectContourCoeEchatData")).done(function(echatData){
		createEchat(echatData.res, 2);
		JyyModelLoading.end("secondEchartDiv");
	});
}
function getContourDBIEchart() {
	JyyModelLoading.start("thirdEchartDiv");
	$.when(getEcahtData({projectId:projectId}, "selectContourDBIEchatData")).done(function(echatData){
		createEchat(echatData.res, 3);
		JyyModelLoading.end("thirdEchartDiv");
	});
}
function getClusterScatterEchart() {
	JyyModelLoading.start("fourthEchartDiv");
	$.when(getEcahtData({projectId:projectId}, "selectClusterScatterEchatData")).done(function(echatData){
		createScatterEchat(echatData, 1);
		JyyModelLoading.end("fourthEchartDiv");
	});
}
function getFeatureEchart() {
	JyyModelLoading.start("fifthEchartDiv");
	$.when(getEcahtData({projectId:projectId}, "selectFeatureEchatData")).done(function(echatData){
		createFeatureEchat(echatData, 1);
		JyyModelLoading.end("fifthEchartDiv");
	});
}

function createEchat(echartData, code) {
	var id = "";
	var option = {};
	var	xAxisName = "";
	var yAxisName = "";
	if(code == 1) {
		id = "powerSSEEchart";
		xAxisName = "";
		yAxisName = "";
	} else if(code == 2) {
		id = "contourCoeEchart";
		xAxisName = "";
		yAxisName = "";
	}else if(code == 3) {
		id = "contourDBIEchart";
		xAxisName = "";
		yAxisName = "";
	}
	var xAxisData = [];
	var seriesData = [];
	for(var i = 0; i < echartData.length;i++) {
		xAxisData.push(echartData[i].valuetype);
		seriesData.push(echartData[i].val);
	}
	option = {
	  	tooltip: {
	    	trigger: 'axis',
	    	axisPointer: {
	      		type: 'cross',
	      		label: {
	        		backgroundColor: '#6a7985'
	      		}
	    	},
	    	position: function(point, params, dom, rect, size) {
	        	//其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
	            var x = point[0]; //
	            var y = point[1];
	            var viewWidth = size.viewSize[0];
	            var viewHeight = size.viewSize[1];
	            var boxWidth = size.contentSize[0];
	            var boxHeight = size.contentSize[1];
	            var posX = 0; //x坐标位置
	            var posY = 0; //y坐标位置

	            if (x < boxWidth) { //左边放不开
	            	posX = 5;
	            } else { //左边放的下
	                posX = x - boxWidth;
	            }
	            if (y < boxHeight) { //上边放不开
	                posY = 5;
	            } else { //上边放得下
	                posY = y - boxHeight;
	            }
	            return [posX, posY];
	    	}
	  	},
	  	grid: {
	    	left: '5%',
	    	right: '5%',
	    	bottom: '8%',
	    	containLabel: true
	  	},
	  	xAxis: [{
	    	type: 'category',
	    	name: xAxisName,
	      	boundaryGap: false,
	      	data: xAxisData
	    }],
	  	yAxis: [{
	      	type: 'value',
	      	name: yAxisName
	    }],
	  	series: [{
			type: 'line',
		    data: seriesData
		}]
	};
	var chartDom = document.getElementById(id);
	var myChart = echarts.init(chartDom);
	myChart.clear();
	myChart.setOption(option);
	window.addEventListener("resize", () => {
		if(myChart){
			myChart.resize()
		}
	})
}
function createScatterEchat(echartData, code) {
	if(JSON.stringify(echartData) == '{}') return;
	var id = "";
	var option = {};
	var	xAxisName = "";
	var yAxisName = "";
	if(code == 1) {
		id = "clusterScatterEchart";
		xAxisName = "";
		yAxisName = "";
	}
	var seriesData = [];
	for(let key in echartData) {
		if(key == undefined) continue;
		seriesData.push({
			type: 'scatter',
			symbolSize: 15,
			name: key,
			encode: { tooltip: [0, 1] },
			data: echartData[key]
		});
	}
	option = {
	  	tooltip: { position: 'top' },
	  	legend: {},
	  	grid: {
	    	left: '5%',
	    	right: '5%',
	    	bottom: '15%',
	    	containLabel: true
	  	},
	  	xAxis: [{
	    	type: 'value',
	    	name: xAxisName,
	    }],
	  	yAxis: [{
	      	type: 'value',
	      	name: yAxisName
	    }],
	  	series: seriesData,
	    dataZoom: [{
	        type: "inside",
	    	start: 0,
	    	end: 100
	    },{
	    	start: 0,
	    	end: 100
	    }],
	};
	var chartDom = document.getElementById(id);
	var myChart = echarts.init(chartDom);
	myChart.clear();
	myChart.setOption(option);
	window.addEventListener("resize", () => {
		if(myChart){
			myChart.resize()
		}
	})
}

function createFeatureEchat(echartData, code) {
	if(JSON.stringify(echartData) == '{}') return;
	var id = "";
	var option = {};
	var	xAxisName = "";
	var yAxisName = "";
	if(code == 1) {
		id = "featureEchart";
		xAxisName = "";
		yAxisName = "典型方式";
	}
	var seriesData = [];
	for(let key in echartData.data) {
		if(key == undefined) continue;
		seriesData.push({
			type: 'scatter',
			symbolSize: 15,
			name: key,
			encode: { tooltip: [0, 1] },
			data: echartData.data[key]
		});
	}
	option = {
	  	tooltip: { position: 'top' },
	  	legend: {},
	  	grid: {
	    	left: '5%',
	    	right: '5%',
	    	bottom: '15%',
	    	containLabel: true
	  	},
	  	xAxis: [{
	    	type: 'category',
	    	name: xAxisName,
	    	data: echartData.xx,
	    }],
	  	yAxis: [{
	      	type: 'value',
	      	minInterval: 1,
	      	name: yAxisName
	    }],
	  	series: seriesData,
	    dataZoom: [{
	        type: "inside",
	    	start: 0,
	    	end: 100
	    },{
	    	start: 0,
	    	end: 100
	    }],
	};
	var chartDom = document.getElementById(id);
	var myChart = echarts.init(chartDom);
	myChart.clear();
	myChart.setOption(option);
	window.addEventListener("resize", () => {
		if(myChart){
			myChart.resize()
		}
	})
}

function getEcahtData(args, method){
	var res = $.ajax({
		url: "../g/service/Sample/"+method,
		type:'POST',
		cache:false,
		dataType: "json",
		data:args ? JSON.stringify(args) : null,
		contentType:"application/json",
        success:function(data){
			return data;
        }
	});
	return res;
}
function invoke(url, args, callback){
	var r, op = {
			url: '../g/service/Sample/' + url,
			type:'POST',
			cache:false,
			async:true,
			dataType:'json',
			data:args ? JSON.stringify(args) : null,
			contentType:"application/json"
		};
	if(typeof callback == 'function'){
		op.success = function(data){
			if(data.error)return alert(data.error);
			callback(data);
		}
	} else {
		op.async = false;
		op.success = function(data){
			r = data
		};
	}
	$.ajax(op);
	if(r)if(r.error){
		alert(r.error);
		return null;
	}
	return r;
};
function getQueryString (name){
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	return r ? unescape(r[2]) : null;
}